<?php

namespace App\Http\Controllers\Admin\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use App\Models\Bundle;
use App\Models\BundleRequestLog;
use App\Services\Utils\Guard;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;
use App\Exceptions\ApiAbstractException;
use App\Exceptions\ApiErrCode;
use App\Http\Requests\Admin\v1\CreateBundleRequest;

class BundleController extends ApiController
{
    public function info(Request $request)
    {
        $id = $request->get('id');
        $bundle = Bundle::find($id);
        $this->checkParamError($bundle, trans('checker.check_bundle_id_error'));
        return $this->response(compact('bundle'));
    }
    
    public function create(CreateBundleRequest $request)
    {
        $name = $request->get('name');
        $description = $request->get('description');
        $platform = $request->get('platform');
        $bundle_id = $request->get('bundle_id');
        $user = Guard::customer();

        $bundles = new Bundle;
        $bundles->customer_id = $user['id'];
        $bundles->bundle_id = $bundle_id;
        $bundles->platform = $platform;
        $bundles->name = $name;
        $bundles->description = $description;
        $bundles->save();

        $bundle = $bundles->where(compact('bundle_id'))->first();
        return $this->response(compact('bundle'));
    }
    
    public function update(Request $request)
    {
        $id = $request->get('id');
        $status = $request->get('status');
        
        $bundle = Bundle::find($id);
        $this->checkParamError($bundle, trans('checker.check_bundle_id_error'));
        if($status == 0)
        {
            $bundle->status = 'normal';
            $bundle->save();
        }else
        {
            $bundle->status = 'user-locked';
            $bundle->save();
        }
        return $this->response(compact('bundle'));
    }
    
    public function bundles(Request $request)
    {
        $per_page = $request->per_page;
        $user = Guard::customer();
        $bundles = Bundle::where('customer_id', $user['id'])->paginate($per_page);
        return $this->response(compact('bundles'));
    }
    
    public function logs(Request $request)
    {
        $id = $request->id;
        $per_page = $request->per_page;
        $logs = BundleRequestLog::where('app_id', $id)->paginate($per_page);
        return $this->response(compact('logs'));
    }

    public function delete(Request $request)
    {
        $id = $request->get('id');
        $bundle = Bundle::find($id);
        $this->checkParamError($bundle, trans('checker.check_bundle_id_error'));
        // $bundle->delete();
        return $this->response($bundle->delete());
    }
}
